/*9TplEaXfa57Bdoia7pfxHi8n385xpg3imY0RW75rCu2+CB/ci4eA3CAxFnPwJ0cY*/
import { ajax, base, promptBox, toast, cardCache, getBusinessInfo } from 'nc-lightapp-front';
import { loginContext, getContext, loginContextKeys } from '../../../public/components/arapInitInfo/loginContext';
import { getCheckedRowColvalues } from '../../../public/components/pubUtils/billPubUtil';
import { setAllFieldEditable } from '../publicMethods/pubUtils';
import { floatObj } from '../../../public/components/pubUtils/floatObj.js';
import { func } from 'prop-types';

function Query(that, props, callback) {
    props.search.openAdvSearch(that.verifySearchId, true, () => {
        let isFirstQuery = that.isFirstQuery;
        if (!isFirstQuery) {
            return;
        }
        props.form.setFormItemsDisabled(that.hxgzCode, {
            zjbzRef: true,
            yxwcTxtF: true,
            jfbzRef: true,
            jfbz_dzjbzhlTxtF: true,
            jfbz_dbbhlTxtF: true,
            dfbzRef: true,
            dfbz_dbbhlTxtF: true,
            dfbz_dzjbzhlTxtF: true,
            hxbzRef: false
        });
        //设置默认值
        if (that.arapFlag && 'ar' == that.arapFlag) {
            setDefaultValueAR(that, props, that.cytjCode, that.bfCode, that.dfCode, that.publicCode, that.hxgzCode, false);
        } else if (that.arapFlag && 'ap' == that.arapFlag) {
            setDefaultValueAP(that, props, that.cytjCode, that.bfCode, that.dfCode, that.publicCode, that.hxgzCode, false);
        }
        that.isFirstQuery = false;
        let pk_org = getContext(loginContextKeys.pk_org);
        let org_Name = getContext(loginContextKeys.org_Name);
        if (pk_org && org_Name) {
            props.form.setFormItemsValue(that.cytjCode, { pk_org: { value: pk_org, display: org_Name } });
            callback.call(that, props, that.cytjCode, 'pk_org', { value: pk_org, display: org_Name });
            return;
        }
        //设置常用条件所有字段可编辑
        let arr = [that.cytjCode, that.bfCode, that.dfCode, that.publicCode]
        setAllFieldEditable(props, that.cytjCode, arr, true);
        props.form.setFormItemsDisabled(that.cytjCode, { pk_org: false });
    })
}

function AutoVerify(that, props, callback) {
    props.search.openAdvSearch(that.autoVerifySearchId, true, () => {
        let isFirstAutoVerify = that.isFirstAutoVerify;
        if (!isFirstAutoVerify) {
            return;
        }
        //设置默认值
        if (that.arapFlag && 'ar' == that.arapFlag) {
            setDefaultValueAR(that, props, that.cytjCode_auto, that.bfCode_auto, that.dfCode_auto, that.publicCode_auto, that.hxgzCode_auto, true);
        } else if (that.arapFlag && 'ap' == that.arapFlag) {
            setDefaultValueAP(that, props, that.cytjCode_auto, that.bfCode_auto, that.dfCode_auto, that.publicCode_auto, that.hxgzCode_auto, true);
        }
        that.isFirstAutoVerify = false;
        let pk_org = getContext(loginContextKeys.pk_org);
        let org_Name = getContext(loginContextKeys.org_Name);
        if (pk_org && org_Name) {
            props.form.setFormItemsValue(that.cytjCode_auto, { pk_org: { value: pk_org, display: org_Name } });
            callback.call(that, props, that.cytjCode_auto, 'pk_org', { value: pk_org, display: org_Name });
            return;
        }
        //设置常用条件所有字段可编辑
        let arr = [that.cytjCode_auto, that.bfCode_auto, that.dfCode_auto, that.publicCode_auto]
        setAllFieldEditable(props, that.cytjCode_auto, arr, true);
        props.form.setFormItemsDisabled(that.cytjCode_auto, { pk_org: false });
    });

}

function Verify(that, props) {
    // 前端需要传递（ jf_vos df_vos rule pageId arapFlag, pk_org）
    if (!verifyValidate(that, props)) {
        return;
    }
    let data = {
        jfValues: getCheckedRowColvalues(that.props, that.tableId_bf, [
            'customer', 'pk_deptid', 'pk_psndoc', 'supplier',
            'settleMoney', 'mid_sett', 'disction', 'linkedPk', 'pk_bill', 'pk_item', 'ts'
        ]),
        dfValues: getCheckedRowColvalues(that.props, that.tableId_df, [
            'customer', 'pk_deptid', 'pk_psndoc', 'supplier',
            'settleMoney', 'mid_sett', 'disction', 'linkedPk', 'pk_bill', 'pk_item', 'ts'
        ]),
        jfCode: that.tableId_bf,
        dfCode: that.tableId_df,
        rule: that.rule,
        pageId: that.pagecode,
        arapFlag: that.arapFlag,
        pk_org: props.form.getFormItemsValue(that.cytjCode, 'pk_org').value,
        jf_hxdx: getObjtype(props.form.getFormItemsValue(that.cytjCode, 'jf_hxdxCBox').value),
        df_hxdx: getObjtype(props.form.getFormItemsValue(that.cytjCode, 'df_hxdxCBox').value)
    };
    ajax({
        url: '/nccloud/arap/verify/verify.do',
        data: Object.assign(data, that.dataInSaga),
        success: (res) => {
            let { success, data } = res;
            if (success) {
                if (data) {
                    let index_bf = getSelectedIndex(props, that.tableId_bf);
                    let index_df = getSelectedIndex(props, that.tableId_df);
                    props.cardTable.delRowsByIndex(that.tableId_bf, index_bf, true);
                    props.cardTable.delRowsByIndex(that.tableId_df, index_df, true);
                    that.setBtnVisible(props, false);
                    if (that.arapFlag && 'ar' == that.arapFlag) {
                        props.openTo('/arap/verificationsheet/verifyqueryar/list/index.html', {
                            pks: data,
                            pagecode: '20060VQ_LIST',
                            appcode: '20060VQ'
                        });
                    } else if (that.arapFlag && 'ap' == that.arapFlag) {
                        props.openTo('/arap/verificationsheet/verifyqueryap/list/index.html', {
                            pks: data,
                            pagecode: '20080VQ_LIST',
                            appcode: '20080VQ'
                        });
                    }

                }
            }
        },
        error: function (data) {
            promptBox({ color: 'danger', noCancelBtn: true, content: data.message });
        }
    });
}


function Jfmath(that, props) {
    let jfData = props.cardTable.getCheckedRows(that.tableId_bf);
    //1,如果选中数据为空，清空贷方选中数据
    if (!jfData || jfData.length == 0) {
        props.cardTable.setColValue(that.tableId_df, 'settleMoney', { value: null, display: null });
        props.cardTable.setColValue(that.tableId_df, 'disction', { value: null, display: null });
        props.cardTable.setColValue(that.tableId_df, 'mid_sett', { value: null, display: null });
        props.cardTable.selectAllRows(that.tableId_df, false);
        that.setBtnVisible(props, false);
        return;
    }
    //2,异币种核销，获得选中行中币结算字段sum，依次选中贷方行sum=sum-settleMoney，直到sum=0，如果sum>0,贷方已全部选中，提示：借贷方结算金额不相等
    if (that.isUnsameVerify) {
        let jfSum = getSelectedSumField(props, that.tableId_bf, 'mid_sett');
        selectTableByMidsettMoney(that, props, that.tableId_df, jfSum);
    } else {
        //2,获得选中行本次结算字段sum，依次选中贷方行sum=sum-settleMoney，直到sum=0，如果sum>0,贷方已全部选中，提示：借贷方结算金额不相等
        let jfSum = getSelectedSumField(props, that.tableId_bf, 'settleMoney');
        selectTableBySettMoney(that, props, that.tableId_df, jfSum);
    }

}

function Dfmath(that, props) {
    let dfData = props.cardTable.getCheckedRows(that.tableId_df);
    //1,如果选中数据为空，清空贷方选中数据
    if (!dfData || dfData.length == 0) {
        props.cardTable.setColValue(that.tableId_bf, 'settleMoney', { value: null, display: null });
        props.cardTable.setColValue(that.tableId_bf, 'disction', { value: null, display: null });
        props.cardTable.setColValue(that.tableId_bf, 'mid_sett', { value: null, display: null });
        props.cardTable.selectAllRows(that.tableId_bf, false);
        that.setBtnVisible(props, false);
        return;
    }
    //2,异币种核销，获得选中行中币结算字段sum，依次选中贷方行sum=sum-settleMoney，直到sum=0，如果sum>0,贷方已全部选中，提示：借贷方结算金额不相等
    if (that.isUnsameVerify) {
        let dfSum = getSelectedSumField(props, that.tableId_df, 'mid_sett');
        selectTableByMidsettMoney(that, props, that.tableId_bf, dfSum);
    } else {
        //2,获得选中行本次结算字段sum，依次选中贷方行sum=sum-settleMoney，直到sum=0，如果sum>0,贷方已全部选中，提示：借贷方结算金额不相等
        let dfSum = getSelectedSumField(props, that.tableId_df, 'settleMoney');
        selectTableBySettMoney(that, props, that.tableId_bf, dfSum);
    }
}


function setDefaultValueAR(that, props, cytjCode, bfCode, dfCode, publicCode, hxgzCode, isauto) {
    if (isauto) {
        cytjCode = that.cytjCode_auto;
        bfCode = that.bfCode_auto;
        dfCode = that.dfCode_auto;
        publicCode = that.publicCode_auto;
        hxgzCode = that.hxgzCode_auto;
    }
    props.form.EmptyAllFormValue(cytjCode);
    props.form.EmptyAllFormValue(hxgzCode);
    if (isauto) {
        props.form.EmptyAllFormValue(that.hxfsCode);
    }

    //设置默认值
    // 本方核销对象		对方核销对象
    props.form.setFormItemsValue(cytjCode, {
        jf_hxdxCBox: { value: 'kh', display: that.state.json['verificationsheet-000000'] },
        df_hxdxCBox: { value: 'kh', display: that.state.json['verificationsheet-000000'] }
    }); /* 国际化处理： 客户,客户*/
    //	本方单据类型	对方单据类型
    props.form.setFormItemsValue(cytjCode, {
        jfBillTypeBox: { value: 'khys', display: that.state.json['verificationsheet-000040'] },
        dfBillTypeBox: { value: 'khsk', display: that.state.json['verificationsheet-000044'] }
    }); /* 国际化处理： 应收单,收款单*/
    // 红蓝对冲	 同币种核销
    props.form.setFormItemsValue(hxgzCode, {
        hldcChkBox: { value: true, display: that.state.json['verificationsheet-000062'] },
        tbzhxChkBox: { value: true, display: that.state.json['verificationsheet-000062'] }
    }); /* 国际化处理： 是,是*/
    let date = getBusinessInfo().businessDate.substring(0, 10);
    let beginDate = date
    let endDate = date
    // 本方开始日期	本方结束日期
    props.form.setFormItemsValue(cytjCode, { jfBeginDateRef: { value: beginDate }, jfEndDateRef: { value: endDate } });
    // 对方开始日期	对方结束日期
    props.form.setFormItemsValue(cytjCode, { dfBeginDateRef: { value: beginDate }, dfEndDateRef: { value: endDate } });

    let meta = props.meta.getMeta();
    //设置本方对象名称、对方对象名称参照
    meta[bfCode].items.map((item) => {
        if (item.attrcode == 'jf_dxmcRef') {
            item.itemtype = 'refer';
            item.refName = that.state.json['verificationsheet-000038']; /* 国际化处理： 客户档案*/
            item.refcode = 'uapbd/refer/customer/CustomerDefaultTreeGridRef/index';
        }
        return item;
    });
    meta[dfCode].items.map((item) => {
        if (item.attrcode == 'df_dxmcRef') {
            item.itemtype = 'refer';
            item.refName = that.state.json['verificationsheet-000038']; /* 国际化处理： 客户档案*/
            item.refcode = 'uapbd/refer/customer/CustomerDefaultTreeGridRef/index';
        }
        return item;
    });
    props.renderItem('form', bfCode, 'jf_dxmcRef', null);
    props.renderItem('form', dfCode, 'df_dxmcRef', null);

    //设置金额方向不可编辑
    props.form.setFormItemsDisabled(hxgzCode, { jefxCmbBox: true });
}

function setDefaultValueAP(that, props, cytjCode, bfCode, dfCode, publicCode, hxgzCode, isauto) {
    if (isauto) {
        cytjCode = that.cytjCode_auto;
        bfCode = that.bfCode_auto;
        dfCode = that.dfCode_auto;
        publicCode = that.publicCode_auto;
        hxgzCode = that.hxgzCode_auto;
    }
    props.form.EmptyAllFormValue(cytjCode);
    props.form.EmptyAllFormValue(hxgzCode);
    if (isauto) {
        props.form.EmptyAllFormValue(that.hxfsCode);
    }
    // 本方核销对象		对方核销对象
    props.form.setFormItemsValue(cytjCode, {
        jf_hxdxCBox: { value: 'gys', display: that.state.json['verificationsheet-000001'] },
        df_hxdxCBox: { value: 'gys', display: that.state.json['verificationsheet-000001'] }
    }); /* 国际化处理： 供应商,供应商*/
    //	本方单据类型	对方单据类型
    props.form.setFormItemsValue(cytjCode, {
        jfBillTypeBox: { value: 'gysfk', display: that.state.json['verificationsheet-000043'] },
        dfBillTypeBox: { value: 'gysyf', display: that.state.json['verificationsheet-000041'] }
    }); /* 国际化处理： 付款单,应付单*/
    // 红蓝对冲	 同币种核销
    props.form.setFormItemsValue(hxgzCode, {
        hldcChkBox: { value: true, display: that.state.json['verificationsheet-000062'] },
        tbzhxChkBox: { value: true, display: that.state.json['verificationsheet-000062'] }
    }); /* 国际化处理： 是,是*/

    let date = getBusinessInfo().businessDate.substring(0, 10);
    let beginDate = date
    let endDate = date
    // 本方开始日期	本方结束日期
    props.form.setFormItemsValue(cytjCode, { jfBeginDateRef: { value: beginDate }, jfEndDateRef: { value: endDate } });
    // 对方开始日期	对方结束日期
    props.form.setFormItemsValue(cytjCode, { dfBeginDateRef: { value: beginDate }, dfEndDateRef: { value: endDate } });

    //设置本方对象名称、对方对象名称参照
    let meta = props.meta.getMeta();
    meta[bfCode].items.map((item) => {
        if (item.attrcode == 'jf_dxmcRef') {
            item.itemType = 'refer';
            item.refName = that.state.json['verificationsheet-000039']; /* 国际化处理： 供应商档案*/
            item.refcode = 'uapbd/refer/supplier/SupplierRefTreeGridRef/index';
        }
        return item;
    });
    meta[dfCode].items.map((item) => {
        if (item.attrcode == 'df_dxmcRef') {
            item.itemType = 'refer';
            item.refName = that.state.json['verificationsheet-000039']; /* 国际化处理： 供应商档案*/
            item.refcode = 'uapbd/refer/supplier/SupplierRefTreeGridRef/index';
        }
        return item;
    });
    props.renderItem('form', bfCode, 'jf_dxmcRef', null);
    props.renderItem('form', dfCode, 'df_dxmcRef', null);
    //设置金额方向不可编辑
    props.form.setFormItemsDisabled(hxgzCode, { jefxCmbBox: true });
}

function getObjtype(str) {
    if (!str) {
        return
    }
    let objtype = 0;
    if (str == 'kh') {
        objtype = 0
    } else if (str == 'gys') {
        objtype = 1
    } else if (str == 'bm') {
        objtype = 2
    } else if (str == 'ywy') {
        objtype = 3
    }
    return objtype
}

function getSelectedIndex(props, areaCode) {
    let indexArr = [];
    let selData = props.cardTable.getCheckedRows(areaCode);
    if (selData.length == 0 || !selData) {
        return null;
    }
    selData.forEach((val) => {
        if (val.data.selected) {
            indexArr.push(val.index);
        }
    });
    return indexArr;
}

//核销校验
function verifyValidate(that, props) {
    let bfdata = props.cardTable.getCheckedRows(that.tableId_bf);
    let dfdata = props.cardTable.getCheckedRows(that.tableId_df);
    if ((!bfdata || bfdata == null || bfdata.length == 0) && (!dfdata || dfdata == null || dfdata.length == 0)) {
        toast({ content: that.state.json['verificationsheet-000053'], color: 'warning' }); /* 国际化处理： 请先选择对应的单据,再进行核销*/
        return false;
    }

    let jfSum = null;
    let dfSum = null;
    //异币种核销
    if (that.isUnsameVerify) {
        jfSum = getSelectedSumField(props, that.tableId_bf, 'mid_sett');
        dfSum = getSelectedSumField(props, that.tableId_df, 'mid_sett');
        let m_maxError = that.rule[2].m_maxError == null ? 0 : that.rule[2].m_maxError; //允许最大误差
        if (Math.abs(jfSum * 1 - dfSum * 1) > m_maxError * 1) {
            promptBox({
                color: 'warning',
                noCancelBtn: true,
                content:
                    that.state.json['verificationsheet-000054'] /* 国际化处理： 非严格匹配（手工核销）异币种核销时，借贷方结算中间币种金额总和不在允许误差范围之内。*/ +
                    that.state.json['verificationsheet-000055'] +
                    jfSum /* 国际化处理：   借方结算中间币种金额总和：*/ +
                    that.state.json['verificationsheet-000056'] +
                    dfSum /* 国际化处理：   贷方结算中间币种金额总和：*/ +
                    that.state.json['verificationsheet-000057'] +
                    m_maxError /* 国际化处理：   允许最大误差范围：*/
            });
            return false;
        }
    } else {
        jfSum = getSelectedSumField(props, that.tableId_bf, 'settleMoney');
        dfSum = getSelectedSumField(props, that.tableId_df, 'settleMoney');
        if (jfSum != dfSum) {
            promptBox({
                color: 'warning',
                noCancelBtn: true,
                content:
                    that.state.json['verificationsheet-000058'] /* 国际化处理： 非严格匹配（手工核销）同币种核销时，借贷方结算原币金额总和不相等。*/ +
                    that.state.json['verificationsheet-000059'] +
                    jfSum /* 国际化处理： 借方结算原币金额总和：*/ +
                    that.state.json['verificationsheet-000060'] +
                    dfSum /* 国际化处理：   贷方结算原币金额总和：*/
            });
            return false;
        }
    }
    return true;
}

//获得选中行数据本次结算金额sum
function getSelectedSumField(props, areaCode, field) {
    let sum = 0;
    let selectedData = props.cardTable.getCheckedRows(areaCode);
    if (selectedData.length != 0 && selectedData) {
        selectedData.forEach((val) => {
            if (val.data.selected) {
                let fieldValue = val.data.values[field].value;
                fieldValue = Number(fieldValue);
                if (!isNaN(fieldValue)) {
                    sum = floatObj.add(sum, fieldValue);
                }
            }
        });
    }
    return sum;
}

//根据选中行中币结算金额sum选中另一区域行
function selectTableByMidsettMoney(that, props, areaCode, sum) {
    //props.cardTable.selectAllRows(areaCode, false);
    props.cardTable.setStatus(areaCode, 'edit');
    let selectdata = props.cardTable.getCheckedRows(areaCode);
    let rownum = props.cardTable.getNumberOfRows(areaCode);//getNumberOfRows获取可见行数，如果是需求需要匹配筛选后数据，需要此方法能过滤界面筛选后即可
    let dealType = true;//折算方式，true乘法，false 除法
    if (rownum == 0) {
        return;
    }
    if(areaCode== that.tableId_df&&!that.rule[2].devMode_credit){
            dealType = false;
    }else if(areaCode== that.tableId_bf&&!that.rule[2].devMode_debit){
            dealType = false;
    }
    let mid_scale = that.rule[2].m_verifyCurrPrecision; //中间币种小数精度;
    let scale = props.cardTable.getValByKeyAndIndex(areaCode, 0, 'money_bal').scale;

    props.cardTable.setColValue(areaCode, 'mid_sett', { value: null, display: null });
    props.cardTable.setColValue(areaCode, 'settleMoney', { value: null, display: null });
    that.retIndex = [];
    if (selectdata && selectdata.length != 0) {
        //返回sum不为0 后续排除改数组的index进行匹配
        var orisum = sum;
        sum = priorityMatchesSelected(that, props, areaCode, 1, sum, scale, mid_scale,dealType);
        if ((that.retIndex && that.retIndex.length == 0) || sum == 0 || ((orisum < 0 && sum > 0) || (orisum > 0 && sum < 0))) {
            //去除多余的行
            reSelectRows(that, props, areaCode);
            return
        }
        selectdata = filterSelected(that, props, areaCode, that.retIndex);
    }
    let selectFlag = false;//勾选标记
    if (that.retIndex && that.retIndex.length != 0) {
        selectFlag = true;//匹配勾选启动
    }
    if(floatObj.multiply(orisum,sum)<0&&selectFlag){
        //匹配行，大于被匹配行，重新获取选中行
         selectdata = props.cardTable.getCheckedRows(areaCode);//获取选中行

    }
    let needSelIndex = [];
    let m_bz2zjbzHL = null;
    if (areaCode == that.tableId_df) {
        m_bz2zjbzHL = that.rule[2].m_dfbz2zjbzHL; //贷方币种对中间币种汇率
    } else {
        m_bz2zjbzHL = that.rule[2].m_jfbz2zjbzHL; //借方币种对中间币种汇率
    }
    if (sum > 0) {
        for (let i = 0; i < rownum; i++) {
            if (selectFlag&&(selectdata.length - i <=0) ) {
                continue;
            }
            let j = selectdata && selectdata.length != 0 ? selectdata[i].index : i;
            let money_bal = props.cardTable.getValByKeyAndIndex(areaCode, j, 'money_bal').value;
            money_bal = Number(money_bal);
            if (sum == 0 || money_bal < 0) {
                // break;
            }
            let sum1 = sum;
            if (!isNaN(money_bal)) {
                let dealmoney = dealType?floatObj.divide(money_bal * 1, m_bz2zjbzHL):floatObj.multiply(money_bal * 1, m_bz2zjbzHL);
                sum = floatObj.subtract(sum,dealmoney ).toFixed(mid_scale);
            }
            needSelIndex.push(j);
            let mid_sett = 0;
            if (sum <= 0) {
                // mid_sett = floatObj.add(sum, floatObj.multiply(money_bal * 1, m_bz2zjbzHL).toFixed(mid_scale) * 1).toFixed(mid_scale);
                mid_sett = sum1;
                props.cardTable.setValByKeyAndIndex(areaCode, j, 'mid_sett', { value: mid_sett, display: mid_sett });
                let settleMoney =!dealType? floatObj.divide(mid_sett * 1, m_bz2zjbzHL).toFixed(scale):floatObj.multiply(mid_sett * 1, m_bz2zjbzHL).toFixed(scale);;
                props.cardTable.setValByKeyAndIndex(areaCode, j, 'settleMoney', {
                    value: settleMoney,
                    display: settleMoney
                });
                break;
            }
            mid_sett = dealType?floatObj.divide(money_bal * 1, m_bz2zjbzHL).toFixed(mid_scale):floatObj.multiply(money_bal * 1, m_bz2zjbzHL).toFixed(mid_scale);
            props.cardTable.setValByKeyAndIndex(areaCode, j, 'mid_sett', { value: mid_sett, display: mid_sett });
            money_bal = money_bal.toFixed(scale);
            props.cardTable.setValByKeyAndIndex(areaCode, j, 'settleMoney', { value: money_bal, display: money_bal });
        }
        let m_maxError = that.rule[2].m_maxError == null ? 0 : that.rule[2].m_maxError; //允许最大误差
        if (sum > 0 && sum > m_maxError * 1) {
            props.cardTable.setColValue(areaCode, 'mid_sett', { value: null, display: null });
            props.cardTable.setColValue(areaCode, 'settleMoney', { value: null, display: null });
            props.cardTable.selectAllRows(areaCode, false);
            promptBox({
                color: 'warning',
                content: that.state.json['verificationsheet-000054']
            }); /* 国际化处理： 非严格匹配（手工核销）异币种核销时，借贷方结算中间币种金额总和不在允许误差范围之内。*/
            return;
        }
        props.cardTable.selectRowsByIndex(areaCode, needSelIndex);
        that.retIndex = [];
    } else if (sum < 0) {
        for (let i = 0; i < rownum; i++) {
            if (selectFlag&&( selectdata.length - i < 0) ) {
                continue;
            }
            let j = selectdata && selectdata.length != 0 ? selectdata[i].index : i;
            let money_bal = props.cardTable.getValByKeyAndIndex(areaCode, j, 'money_bal').value;
            money_bal = Number(money_bal);
            if (sum == 0 || money_bal > 0) {
                // continue
            }
            if (!isNaN(money_bal)) {
                let dealmoney = dealType?floatObj.divide(money_bal * 1, m_bz2zjbzHL):floatObj.multiply(money_bal * 1, m_bz2zjbzHL);
                sum = floatObj.subtract(sum,dealmoney ).toFixed(mid_scale);
            }
            needSelIndex.push(j);
            let mid_sett = 0;
            if (sum > 0) {
                let oriMoney = dealType?floatObj.divide(money_bal * 1, m_bz2zjbzHL):floatObj.multiply(money_bal * 1, m_bz2zjbzHL);
                mid_sett = floatObj.add(sum, oriMoney);
                let settle =!dealType?floatObj.divide(mid_sett * 1,m_bz2zjbzHL):floatObj.multiply(mid_sett * 1,m_bz2zjbzHL);
                props.cardTable.setValByKeyAndIndex(areaCode, j, 'mid_sett', { value: mid_sett, display: mid_sett });
                props.cardTable.setValByKeyAndIndex(areaCode, j, 'settleMoney', {
                    value: settle,
                    display:settle
                });
                break;
            }
            mid_sett =dealType?floatObj.divide(money_bal * 1, m_bz2zjbzHL).toFixed(mid_scale):floatObj.multiply(money_bal * 1, m_bz2zjbzHL).toFixed(mid_scale);
            props.cardTable.setValByKeyAndIndex(areaCode, j, 'mid_sett', { value: mid_sett, display: mid_sett });
            money_bal = money_bal.toFixed(scale);
            props.cardTable.setValByKeyAndIndex(areaCode, j, 'settleMoney', { value: money_bal, display: money_bal });
        }
        let m_maxError = that.rule[2].m_maxError == null ? 0 : that.rule[2].m_maxError; //允许最大误差
        if (sum < 0 && Math.abs(sum) > m_maxError) {
            props.cardTable.setColValue(areaCode, 'mid_sett', { value: null, display: null });
            props.cardTable.setColValue(areaCode, 'settleMoney', { value: null, display: null });
            props.cardTable.selectAllRows(areaCode, false);
            promptBox({
                color: 'warning',
                content: that.state.json['verificationsheet-000054']
            }); /* 国际化处理： 非严格匹配（手工核销）异币种核销时，借贷方结算中间币种金额总和不在允许误差范围之内。*/
            return;
        }
        props.cardTable.selectRowsByIndex(areaCode, needSelIndex);
        that.retIndex = [];
    }
}

//根据选中行结算金额sum选中另一区域行
function selectTableBySettMoney(that, props, areaCode, sum) {
    //props.cardTable.selectAllRows(areaCode, false);
    props.cardTable.setStatus(areaCode, 'edit');
    let selectdata = props.cardTable.getCheckedRows(areaCode);//获取选中行
    let rownum = props.cardTable.getNumberOfRows(areaCode);
    if (rownum == 0) {
        return;
    }
    
    //props.cardTable.setColValue(areaCode, 'settleMoney', { value: null, display: null }); 
    // props.cardTable.setColValue(areaCode, 'disction', { value: null, display: null });
    let scale = props.cardTable.getValByKeyAndIndex(areaCode, 0, 'money_bal').scale;
    var orisum = sum; //存储原始sum
    that.retIndex = []; //存取勾选返回的下标
    if (selectdata && selectdata.length != 0) {
        //返回数组 如果数组长度为0，则证明不用匹配，如果长度不为0 后续排除改数组的index进行匹配
        sum = priorityMatchesSelected(that, props, areaCode, 0, sum, scale, null,null);
        if ((that.retIndex && that.retIndex.length == 0) || sum == 0||((orisum < 0 && sum > 0)  )) {//||(orisum > 0 && sum < 0)
            reSelectRows(that, props, areaCode);
            return
        }
        selectdata = filterSelected(that, props, areaCode, that.retIndex);//去掉勾选，剩下的数据
    }
    let selectFlag = false;//勾选标记
    if (that.retIndex && that.retIndex.length!= 0) {
        selectFlag = true;//匹配勾选启动
    }
    let isEdit = false;
    if(floatObj.multiply(orisum,sum)<0&&selectFlag){
             //匹配行，大于被匹配行，重新获取选中行,证明选中的足够去匹配了
            selectdata = props.cardTable.getCheckedRows(areaCode);//获取选中行 
            sum = orisum;

    }
    if (sum > 0) {//无论勾选与否，此时数据settel都是0
        let needSelIndex = [];
        for (let i = 0; i < rownum; i++) {
            if (selectFlag&&(selectdata.length - i <=0) ) {
                continue;
            }
            let j = selectdata && selectdata.length != 0  ? selectdata[i].index :i;
            let money_bal =props.cardTable.getValByKeyAndIndex(areaCode, j, 'money_bal').value;
            money_bal = Number(money_bal);
            if (sum <= 0 || money_bal < 0) {
                continue;
            }
            if (!isNaN(money_bal)) {
                sum = floatObj.subtract(sum, money_bal);
            }
            needSelIndex.push(j);
            let settleMoney = 0;
            if (sum < 0) {
                settleMoney = floatObj.add(sum, money_bal).toFixed(scale);
                props.cardTable.setValByKeyAndIndex(areaCode, j , 'settleMoney', {
                    value: settleMoney,
                    display: settleMoney
                });
                props.cardTable.setValByKeyAndIndex(areaCode, j , 'disction', { value: null, display: null });
                break;
            }
            settleMoney = money_bal.toFixed(scale);
            props.cardTable.setValByKeyAndIndex(areaCode, j , 'settleMoney', {
                value: settleMoney,
                display: settleMoney
            });
            props.cardTable.setValByKeyAndIndex(areaCode, j , 'disction', { value: null, display: null });
        }
        if (that.retIndex.length+needSelIndex.length !=rownum &&sum > 0) {
            props.cardTable.setColValue(areaCode, 'settleMoney', { value: null, display: null });
            props.cardTable.setColValue(areaCode, 'disction', { value: null, display: null });
            props.cardTable.selectAllRows(areaCode, false);
            promptBox({
                color: 'warning',
                noCancelBtn: true,
                content: that.state.json['verificationsheet-000061']
            }); /* 国际化处理： 借贷方结算金额不相等！*/
            return;
        }
        props.cardTable.selectRowsByIndex(areaCode, needSelIndex);
        that.retIndex = [];
    } else if (sum < 0) {
        let needSelIndex = [];
        for (let i = 0; i < rownum; i++) {
            if ((selectFlag&&(selectdata.length - i <=0))||sum>0 ) {
                continue;
            }
            let j = selectdata && selectdata.length != 0 ? selectdata[i].index : i;
            let money_bal = props.cardTable.getValByKeyAndIndex(areaCode, j, 'money_bal').value;
            money_bal = Number(money_bal);
            if ((sum >= 0 )||(money_bal>0&&!isEdit)) {
            continue;
            }
            if (!isNaN(money_bal)) {
                sum = floatObj.subtract(sum, money_bal);
            }
            needSelIndex.push(j);
            let settleMoney = 0;
            if (sum > 0) {
                settleMoney = floatObj.add(sum, money_bal).toFixed(scale);
                props.cardTable.setValByKeyAndIndex(areaCode, j , 'settleMoney', {
                    value: settleMoney,
                    display: settleMoney
                });
                props.cardTable.setValByKeyAndIndex(areaCode, j , 'disction', { value: null, display: null });
                break;
            }
            settleMoney = money_bal.toFixed(scale);
            props.cardTable.setValByKeyAndIndex(areaCode, j , 'settleMoney', {
                value: settleMoney,
                display: settleMoney
            });
            props.cardTable.setValByKeyAndIndex(areaCode, i, 'disction', { value: null, display: null });
        }
        if (that.retIndex.length+needSelIndex.length !=rownum &&sum < 0) {
            if(orisum>0){
                //对方
                let selMoney  =  props.cardTable.getValByKeyAndIndex(areaCode, that.retIndex, 'settleMoney').value;
                let newMoney = floatObj.add(selMoney,sum);
                props.cardTable.setValByKeyAndIndex(areaCode,that.retIndex, 'settleMoney', { value: newMoney, display: newMoney });
                needSelIndex.push(that.retIndex)
            }else{
                props.cardTable.setColValue(areaCode, 'settleMoney', { value: null, display: null });
                props.cardTable.setColValue(areaCode, 'disction', { value: null, display: null });
                props.cardTable.selectAllRows(areaCode, false);
                promptBox({
                    color: 'warning',
                    noCancelBtn: true,
                    content: that.state.json['verificationsheet-000061']
                }); /* 国际化处理： 借贷方结算金额不相等！*/
                return;
            }
           
           
        }
        props.cardTable.selectRowsByIndex(areaCode, needSelIndex);
        that.retIndex = [];
    }
}
/**
 * 优先匹配勾选数据
 * @param {*} that 
 * @param {*} props 
 * @param {*} areaCode 
 * @param {*} verifyType  0：同币种， 1：异币种
 * @param {*} sum 
 */
function priorityMatchesSelected(that, props, areaCode, verifyType, sum, scale, mid_scale,dealType) {
    let selectedData = props.cardTable.getCheckedRows(areaCode);
    let selectLength = selectedData.length;
    that.retIndex = [];//使用前先清空
    if (verifyType == 0) {
        if (sum > 0) {
            for (var j = 0; j < selectedData.length; j++) {
                var i = selectedData[j].index;
                var money_bal = selectedData[j].data.values["money_bal"].value;
                money_bal = Number(money_bal);
                if (sum == 0 || money_bal == 0) {
                    props.cardTable.setValByKeyAndIndex(areaCode, i, 'settleMoney', {
                        value: null,
                        display: null
                    });
                    props.cardTable.setValByKeyAndIndex(areaCode, i, 'disction', { value: null, display: null });
                    continue;
                }
                if (!isNaN(money_bal)) {
                    sum = floatObj.subtract(sum, money_bal);
                }
                that.retIndex.push(i);
                let  settleMoney = 0;
                if (sum < 0) {
                    settleMoney = floatObj.add(sum, money_bal).toFixed(scale);
                    props.cardTable.setValByKeyAndIndex(areaCode, i, 'settleMoney', {
                        value: settleMoney,
                        display: settleMoney
                    });
                    props.cardTable.setValByKeyAndIndex(areaCode, i , 'disction', { value: null, display: null });
                    break;
                }
                settleMoney = money_bal.toFixed(scale);
                props.cardTable.setValByKeyAndIndex(areaCode, i , 'settleMoney', {
                    value: settleMoney,
                    display: settleMoney
                });
                props.cardTable.setValByKeyAndIndex(areaCode, i, 'disction', { value: null, display: null });
            }
            props.cardTable.selectRowsByIndex(areaCode, that.retIndex);
            return sum
        } else if (sum < 0) {
            for (var j = 0; j < selectedData.length; j++) {
                var money_bal = selectedData[j].data.values["money_bal"].value;
                money_bal = Number(money_bal);
                if (sum == 0 || money_bal == 0) {
                    props.cardTable.setValByKeyAndIndex(areaCode, i, 'settleMoney', {
                        value: null,
                        display: null
                    });
                    props.cardTable.setValByKeyAndIndex(areaCode, i, 'disction', { value: null, display: null });
                    continue;
                }
                var i = selectedData[j].index;
                if (!isNaN(money_bal)) {
                    sum = floatObj.subtract(sum, money_bal);
                }
                that.retIndex.push(i);
                let  settleMoney = 0;
                if (sum > 0) {
                    settleMoney = floatObj.add(sum, money_bal).toFixed(scale);
                    props.cardTable.setValByKeyAndIndex(areaCode, i , 'settleMoney', {
                        value: settleMoney,
                        display: settleMoney
                    });
                    props.cardTable.setValByKeyAndIndex(areaCode, i , 'disction', { value: null, display: null });
                    break;
                }
                settleMoney = money_bal.toFixed(scale);
                props.cardTable.setValByKeyAndIndex(areaCode, i , 'settleMoney', {
                    value: settleMoney,
                    display: settleMoney
                });
                props.cardTable.setValByKeyAndIndex(areaCode, i, 'disction', { value: null, display: null });

            };
            props.cardTable.selectRowsByIndex(areaCode, that.retIndex);
            return sum
        }
    } else {
        let m_bz2zjbzHL = null;
        if (areaCode == that.tableId_df) {
            m_bz2zjbzHL = that.rule[2].m_dfbz2zjbzHL; //贷方币种对中间币种汇率
        } else {
            m_bz2zjbzHL = that.rule[2].m_jfbz2zjbzHL; //借方币种对中间币种汇率
        }
        if (sum > 0) {
            for (var k = 0; k < selectLength; k++) {
                var data = selectedData[k];
                var i = data.index;
                var money_bal = data.data.values["money_bal"].value;
                money_bal = Number(money_bal);
                //、、
                let sum1 = sum;
                if (sum ==  0 || money_bal == 0) {
                    // mid_sett = floatObj.add(sum, floatObj.multiply(money_bal * 1, m_bz2zjbzHL).toFixed(mid_scale) * 1).toFixed(mid_scale);
                    // mid_sett = sum1;
                    // props.cardTable.setValByKeyAndIndex(areaCode, i, 'mid_sett', { value: mid_sett, display: mid_sett });
                    // let settleMoney = floatObj.divide(mid_sett * 1, m_bz2zjbzHL).toFixed(scale);
                    // props.cardTable.setValByKeyAndIndex(areaCode, i, 'settleMoney', {
                    //     value: settleMoney,
                    //     display: settleMoney
                    // });
                    props.cardTable.setValByKeyAndIndex(areaCode, i, 'settleMoney', {
                            value: null,
                            display: null
                        });
                    break;
                }
                if (!isNaN(money_bal)) {
                    if(dealType){
                        sum = floatObj.subtract(sum, floatObj.divide(money_bal * 1, m_bz2zjbzHL)).toFixed(mid_scale);
                    }else{
                        sum = floatObj.subtract(sum, floatObj.multiply(money_bal * 1, m_bz2zjbzHL)).toFixed(mid_scale);
                    }
                    
                }
                let mid_sett = 0;
                that.retIndex.push(i);
                let  settleMoney = 0;
                if (sum <= 0) {
                    // mid_sett = floatObj.add(sum, floatObj.multiply(money_bal * 1, m_bz2zjbzHL).toFixed(mid_scale) * 1).toFixed(mid_scale);
                    mid_sett = sum1;
                    props.cardTable.setValByKeyAndIndex(areaCode, i, 'mid_sett', { value: mid_sett, display: mid_sett });
                    settleMoney =!dealType?floatObj.divide(mid_sett * 1, m_bz2zjbzHL).toFixed(scale): floatObj.multiply(mid_sett * 1, m_bz2zjbzHL).toFixed(scale);
                    props.cardTable.setValByKeyAndIndex(areaCode, i, 'settleMoney', {
                        value: settleMoney,
                        display: settleMoney
                    });
                    break;
                }
                mid_sett = dealType?floatObj.divide(money_bal * 1, m_bz2zjbzHL).toFixed(mid_scale):floatObj.multiply(money_bal * 1, m_bz2zjbzHL).toFixed(mid_scale);
                props.cardTable.setValByKeyAndIndex(areaCode, i, 'mid_sett', { value: mid_sett, display: mid_sett });
                money_bal = money_bal.toFixed(scale);
                props.cardTable.setValByKeyAndIndex(areaCode, i, 'settleMoney', { value: money_bal, display: money_bal });
            };
            props.cardTable.selectRowsByIndex(areaCode, that.retIndex);
            return sum;
        } else if (sum < 0) {
            for (var k = 0; k < selectedData.length; k++) {
                var data = selectedData[k];
                var i = data.index;
                var money_bal = data.data.values["money_bal"].value;
                money_bal = Number(money_bal);
                if (sum == 0 || money_bal == 0) {
                    // mid_sett = floatObj.add(sum, floatObj.multiply(money_bal * 1, m_bz2zjbzHL).toFixed(mid_scale));
                    // props.cardTable.setValByKeyAndIndex(areaCode, i, 'mid_sett', { value: mid_sett, display: mid_sett });
                    // props.cardTable.setValByKeyAndIndex(areaCode, i, 'settleMoney', {
                    //     value: mid_sett * 1 / m_bz2zjbzHL,
                    //     display: mid_sett * 1 / m_bz2zjbzHL
                    // });
                    props.cardTable.setValByKeyAndIndex(areaCode, i, 'mid_sett', { value: mid_sett, display: mid_sett });
                    props.cardTable.setValByKeyAndIndex(areaCode, i, 'settleMoney', {
                        value:null,
                        display: null,
                    });
                    break;
                }
                if (!isNaN(money_bal)) {
                    let dealmoney = dealType?floatObj.divide(money_bal * 1, m_bz2zjbzHL): floatObj.multiply(money_bal * 1, m_bz2zjbzHL);
                    sum = floatObj.subtract(sum, dealmoney).toFixed(mid_scale);
                }
                let mid_sett = 0;
                that.retIndex.push(i);
                if (sum > 0) {
                    mid_sett = floatObj.add(sum, floatObj.multiply(money_bal * 1, m_bz2zjbzHL).toFixed(mid_scale));
                    let settle =!dealType?floatObj.divide(mid_sett * 1,m_bz2zjbzHL):floatObj.multiply(mid_sett * 1,m_bz2zjbzHL);
                    props.cardTable.setValByKeyAndIndex(areaCode, i, 'mid_sett', { value: mid_sett, display: mid_sett });
                    props.cardTable.setValByKeyAndIndex(areaCode, i, 'settleMoney', {
                        value: settle,
                        display:settle
                    });
                    break;
                }
                mid_sett = dealType?floatObj.divide(money_bal * 1, m_bz2zjbzHL).toFixed(mid_scale):floatObj.multiply(money_bal * 1, m_bz2zjbzHL).toFixed(mid_scale);
                props.cardTable.setValByKeyAndIndex(areaCode, i, 'mid_sett', { value: mid_sett, display: mid_sett });
                money_bal = money_bal.toFixed(scale);
                props.cardTable.setValByKeyAndIndex(areaCode, i, 'settleMoney', { value: money_bal, display: money_bal });
            };
            props.cardTable.selectRowsByIndex(areaCode, that.retIndex);
            return sum;
        }
    }
}
/**
 * 过滤勾选的数据
 * @param {*} that 
 * @param {*} props 
 * @param {*} areaCode 
 * @param {*} that 
 * @param {*} retIndex 
 */
function filterSelected(that, props, areaCode, retIndex) {
    props.cardTable.selectAllRows(areaCode, true);//先全选后放开，没有办法，后续是否能通过一个API获取带index的进行过滤
    let alldata = props.cardTable.getCheckedRows(areaCode);
    props.cardTable.selectAllRows(areaCode, false);
    props.cardTable.selectRowsByIndex(areaCode, retIndex)
    let retdata = []
    for (let i = 0; i < alldata.length; i++) {
        if (retIndex.indexOf(alldata[i].index) != -1) {
            continue;
        }
        retdata.push(alldata[i]);
        props.cardTable.setValByKeyAndIndex(areaCode,i, 'settleMoney', { value: null, display: null });
    }
    return retdata;
}
/**
 * 勾选行远大于被匹配数据时筛掉多余的勾选行
 * @param {*} that 
 * @param {*} props 
 * @param {*} areaCode 
 */
function reSelectRows(that, props, areaCode) {
    props.cardTable.selectAllRows(areaCode, true);
    props.cardTable.selectAllRows(areaCode, false);
    props.cardTable.selectRowsByIndex(areaCode, that.retIndex)
}
/**
 * 核销方案复制
 */
function copyFormBeSureEvent() {
    if (!this.pk_org || this.pk_org == null || this.pk_org == "") {
        toast({ content: this.state.json['verificationsheet-000136'], color: 'danger' }); /* 国际化处理： 请先选择要复制的财务组织再进行复制操作！*/
        this.props.modal.show('Copyform');
        return false;
    }
    ajax({
        url: '/nccloud/arap/verifyfa/copyVerifyScheme.do',
        data: {
            pk_verify_fa: this.pkfa,
            pk_org: this.pk_org
        },
        success: (res) => {
            this.getData();
            if (res) {
                toast({
                    content: this.state.json['verificationsheet-000137'],
                    color: 'success'
                }); /* 国际化处理： 复制成功*/
                if (res.data) {
                    toast({
                        content: res.date, //重复数据
                        color: 'warning'
                    });
                }

            }
        },
        error: function (data) {
            toast({ color: 'danger', content: data.message });
        }
    });
}

function copyFormCloseOrCancel(that) {

    that.props.form.EmptyAllFormValue("Copyform");
    that.copydata = {};
}
/**
 * 批量设置默认核销方案
 * @param {*} that 
 * @param {*} pageCode 
 * @param {*} funCode 
 */
function setDefaultVerfiyFa(that, tableId, pageCode, funCode) {
    let data = that.props.editTable.getCheckedRows(tableId);
    var pkTsMap = {}
    var pks = []
    let onlyTs = null
    for (let i = 0; i < data.length; i++) {
        let pk = data[i].data.values.pk_verify_fa.value;
        let ts = data[i].data.values.ts.value;
        pkTsMap[pk] = ts;
        pks[i] = pk;
    }
    if (data.length == 1) {
        onlyTs = data[0].data.values.ts.value;
    }
    ajax({
        url: '/nccloud/arap/verifyfa/setdefault.do',
        data: {
            pk_bills: pks,
            pkTsMap: pkTsMap,
            pageId: pageCode,
            ts: onlyTs,
            funCode: funCode
        },
        success: (res) => {
            if (res) {
                that.props.editTable.setTableData(tableId, res.data[tableId]);
                toast({
                    content: that.state.json['verificationsheet-000094'],
                    color: 'success'
                }); /* 国际化处理： 操作成功*/
            }
        },
        error: function (data) {
            toast({ color: 'error', content: data.message });
        }
    });
}


export {
    Query,
    AutoVerify,
    Verify,
    Jfmath,
    Dfmath,
    setDefaultValueAR,
    setDefaultValueAP,
    copyFormBeSureEvent,
    copyFormCloseOrCancel,
    setDefaultVerfiyFa
}
/*9TplEaXfa57Bdoia7pfxHi8n385xpg3imY0RW75rCu2+CB/ci4eA3CAxFnPwJ0cY*/